/**
 * Created by xuweijie on 2018/1/19.
 */
layui.use(['element', 'layer', 'form', 'table'], function () {
    var element = layui.element;
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;
    var tableInfo = table.render({
        id: 'cloudHouseTableId',
        elem: '#cloudHouseTable',
        url: '/admin/house/cloudHouseInfo',
        method: 'post',
        page: true,
        limit: 10,
        loading: true,
        skin: 'row',
        even: true,
        text: {
            none: '暂无相关数据'
        },
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'id', title: '序号', type: 'numbers', unresize: true, sort: true, width: 80, fixed: 'left'}
            , {field: 'cloudId', title: '云图ID', sort: true, unresize: true, width: 80}
            , {field: 'name', title: '名称', align: 'center'}
            , {field: 'address', title: '详细地址'}
            , {field: 'lon', title: '经度', align: 'center'}
            , {field: 'lat', title: '纬度', align: 'center'}
            , {field: 'statusStr', title: '状态', unresize: true, align: 'center', width: 80}
            , {field: 'createTime', title: '创建时间', sort: true, unresize: true, align: 'center'}
            , {fixed: 'right', title: '操作', width: 150, align: 'center', unresize: true, toolbar: '#oreationBtn'}
        ]]
    });

    table.on('tool(cloudTableInfo)', function (obj) {
        var data = obj.data;//当前行数据
        var layEvent = obj.event;////获得 lay-event 对应的值
        var tr = obj.tr; //获得当前行 tr 的DOM对象
        if (layEvent === 'detail') { //详情
            detailFunction(obj);
        } else if (layEvent === 'del') { //删除
            deleteFunction(obj);
        } else if (layEvent === 'update') { //更新
           updateFunction(obj);
        }
    });

    //批量删除
    var active = {
        deleteHouse: function () {
            var checkStatus = table.checkStatus('cloudHouseTableId')
                , data = checkStatus.data;
            if (data.length > 50) {
                layer.msg("超过最大数量限制");
                return;
            }
            layer.open({
                type: 1,
                title: false,
                closeBtn: 2,
                resize: false,
                content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">' +
                '(涉及地图的显示,请慎重)是否需要删除?删除后将不可恢复</div>',
                area: '30%',
                shade: 0.8,
                shadeClose: true,
                anim: 1,
                id: 'LAY_layuiprodel', //设定一个id，防止重复弹出
                btn: ['绝不后悔', '我怂了'],
                moveType: 1,
                yes: function (index, layero) {
                    var params = $.param({
                        myData: JSON.stringify(data)
                    }, true);
                    $.ajax({
                        url: '/admin/house/deleteCloudDataBatch',
                        type: 'post',
                        data: params,
                        dataType: 'json',
                        success: function (e) {
                            layer.msg(e.msg);
                            layer.close(index);
                            if (e.msg == "删除成功") {
                                tableInfo.reload({ //执行重载
                                    page: {
                                        curr: 1 //重新从第 1 页开始
                                    },
                                    done: function (res, curr, count) {
                                        this.where = {};
                                    }
                                });
                            }
                        }
                    })
                }
            });
        },

        addOneHouse: function () { //单次添加
            var content = $('#addOneCloudData');
            $('#cloudDetail').hide();
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: ['单次添加', 'font-size:18px;'],
                closeBtn: 1,
                shade: 0.3,
                content: content,
                area: ['50%', '70%'],
                shadeClose: true,
                resize: true,
                anim: 1,
                id: 'LAY_layuiroleasone', //设定一个id，防止重复弹出
                moveType: 1,
                maxmin: false,
                success: function (layero, index) {
                    $('#cloudAddress').val('');
                    $('#cloudDetail').val('');
                    $('#addOneData').text('确认添加');
                    var map = new AMap.Map('container', {
                        resizeEnable: true,
                        zoom: 10
                    });
                    var trafficLayer = new AMap.TileLayer.Traffic({
                        zIndex: 15
                    });
                    trafficLayer.setMap(map);
                    AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {
                        var poiPicker = new PoiPicker({
                            input: 'cloudAddress'
                        });
                        poiPickerReady(poiPicker);
                    });
                    function poiPickerReady(poiPicker) {
                        window.poiPicker = poiPicker;
                        var marker = new AMap.Marker();
                        var infoWindow = new AMap.InfoWindow({
                            offset: new AMap.Pixel(0, -20)
                        });
                        poiPicker.on('poiPicked', function (poiResult) {
                            var source = poiResult.source,
                                poi = poiResult.item,
                                info = {
                                    name: poi.name,
                                    location: poi.location.toString(),
                                    address: poi.district + poi.address
                                };
                            $('#cloudDetail').val(JSON.stringify(info, null, 2));
                            marker.setMap(map);
                            infoWindow.setMap(map);
                            marker.setPosition(poi.location);
                            infoWindow.setPosition(poi.location);
                            infoWindow.setContent('基本信息: <pre>' + JSON.stringify(info, null, 2) + '</pre>');
                            infoWindow.open(map, marker.getPosition());
                        });
                        poiPicker.onCityReady(function () {
                            poiPicker.suggest('地名地址信息');
                        });
                    }

                    var active = {
                        addOneData: function () {
                            var mydata = $('#cloudDetail').val();
                            if (mydata == '') {
                                layer.msg("未选择地点");
                                return;
                            }
                            var params = $.param({
                                myData: mydata
                            }, true);
                            $.ajax({
                                url: '/admin/house/createOneCloudData',
                                type: 'post',
                                data: params,
                                dataType: 'json',
                                success: function (e) {
                                    layer.msg(e.msg);
                                    layer.close(index);
                                    if (e.msg == "添加成功") {
                                        tableInfo.reload({
                                            page: {
                                                curr: 1
                                            },
                                            done: function (res, curr, count) {
                                                this.where = {};
                                            }
                                        });
                                    }
                                }
                            })
                        },
                        resetOneData: function () {
                            $('#cloudAddress').val('');
                            $('#cloudDetail').val('');
                        }
                    };
                    $('.addOneCloudDataclass .layui-btn').on('click', function () {
                        var type = $(this).data('type');
                        active[type] ? active[type].call(this) : '';
                    });
                },
                cancel: function () {
                    $('#cloudAddress').val('');
                    $('#cloudDetail').val('');
                }
            });
        },

        addBatchHouse: function () {  //批量添加
            var content = '';
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: ['批量添加', 'font-size:18px;'],
                closeBtn: 1,
                shade: 0.3,
                content: content,
                area: ['50%', '50%'],
                shadeClose: true,
                resize: true,
                anim: 1,
                id: 'LAY_layuiroleabatch', //设定一个id，防止重复弹出
                moveType: 1,
                maxmin: false,
                success: function (layero, index) {

                },
                cancel: function () {

                }
            });
        }
    };

    //全局操作按钮
    $('.AllBtnController .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    function deleteFunction(obj) {
        layer.open({
            type: 1,
            title: false,
            closeBtn: 2,
            resize: true,
            content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">' +
            '(涉及地图的显示,请慎重)是否需要删除?删除后将不可恢复</div>',
            area: '30%',
            shade: 0.8,
            shadeClose: true,
            anim: 1,
            id: 'LAY_layuiprodel', //设定一个id，防止重复弹出
            btn: ['绝不后悔', '我怂了'],
            moveType: 1,
            yes: function (index, layero) {
                var params = $.param({
                    myData: JSON.stringify(obj.data)
                }, true);
                $.ajax({
                    url: '/admin/house/deleteCloudData',
                    type: 'post',
                    data: params,
                    dataType: 'json',
                    success: function (e) {
                        layer.msg(e.msg);
                        layer.close(index);
                        if (e.msg == "删除成功") {
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        }
                    }
                })
            }
        });
    }
    
    function updateFunction(obj) {
        $('#cloudfieldTitle').text('更新云图信息,当前云图id: '+obj.data.cloudId);
        var content = $('#addOneCloudData');
        $('#cloudDetail').hide();
        layer.open({
            type: 1,
            skin: 'layui-layer-molv',
            title: ['更新云图数据', 'font-size:18px;'],
            closeBtn: 1,
            shade: 0.3,
            content: content,
            area: ['50%', '70%'],
            shadeClose: true,
            resize: true,
            anim: 1,
            id: 'LAY_layuiroupdate', //设定一个id，防止重复弹出
            moveType: 1,
            maxmin: false,
            success: function (layero, index) {
                $('#cloudAddress').val(obj.data.address+obj.data.name);
                $('#cloudDetail').val('');
                $('#addOneData').text('确认更新');
                var map = new AMap.Map('container', {
                    resizeEnable: true,
                    zoom: 10
                });
                var trafficLayer = new AMap.TileLayer.Traffic({
                    zIndex: 15
                });
                trafficLayer.setMap(map);
                AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {
                    var poiPicker = new PoiPicker({
                        input: 'cloudAddress'
                    });
                    poiPickerReady(poiPicker);
                });
                function poiPickerReady(poiPicker) {
                    window.poiPicker = poiPicker;
                    var marker = new AMap.Marker();
                    var infoWindow = new AMap.InfoWindow({
                        offset: new AMap.Pixel(0, -20)
                    });
                    poiPicker.on('poiPicked', function (poiResult) {
                        var source = poiResult.source,
                            poi = poiResult.item,
                            info = {
                                name: poi.name,
                                location: poi.location.toString(),
                                address: poi.district + poi.address
                            };
                        $('#cloudDetail').val(JSON.stringify(info, null, 2));
                        marker.setMap(map);
                        infoWindow.setMap(map);
                        marker.setPosition(poi.location);
                        infoWindow.setPosition(poi.location);
                        infoWindow.setContent('基本信息: <pre>' + JSON.stringify(info, null, 2) + '</pre>');
                        infoWindow.open(map, marker.getPosition());
                    });
                    poiPicker.onCityReady(function () {
                        poiPicker.suggest('地名地址信息');
                    });
                }

                var active = {
                    addOneData: function () {
                        var mydata = $('#cloudDetail').val();
                        if (mydata == '') {
                            layer.msg("未作任何修改或选择地址");
                            return;
                        }
                        var params = $.param({
                            id:obj.data.cloudId,
                            myData: mydata
                        }, true);
                        $.ajax({
                            url: '/admin/house/updateOneCloudData',
                            type: 'post',
                            data: params,
                            dataType: 'json',
                            success: function (e) {
                                layer.msg(e.msg);
                                layer.close(index);
                                if (e.msg == "更新成功") {
                                    //同步更新缓存对应的值
                                    var str = mydata.location.split(",");
                                    obj.update({
                                        name: mydata.name,
                                        address: mydata.address,
                                        lon:str[0],
                                        lat: str[1]
                                    });
                                }
                            }
                        })
                    },
                    resetOneData: function () {
                        $('#cloudAddress').val('');
                        $('#cloudDetail').val('');
                    }
                };
                $('.addOneCloudDataclass .layui-btn').on('click', function () {
                    var type = $(this).data('type');
                    active[type] ? active[type].call(this) : '';
                });
            },
            cancel: function () {
                $('#cloudAddress').val('');
                $('#cloudDetail').val('');
            }
        });
    }

    function detailFunction(obj) {
            layer.open({
                type: 2,
                skin: 'layui-layer-molv',
                title: ['出租房列表: '+obj.data.name+" =============  地址:  "+obj.data.address, 'font-size:18px;'],
                closeBtn: 1,
                shade: 0,
                content: '/admin/houseInfo/houseInfoList?cloudId='+obj.data.cloudId,
                area: ['100%', '100%'],
                shadeClose: true,
                resize: true,
                anim: 1,
                id: 'LAY_layuidetail',
                moveType: 1,
                maxmin: false,
                success: function (layero, index) {

                },
                cancel: function (index, layero) {

                }
            });
    }

    //查询窗口
    $('#findHouse').click(function () {
        var content = $('#findCloudInfo');
        layui.use(['layer', 'form'], function () {
            var layer = layui.layer;
            var form = layui.form;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: ['查询', 'font-size:18px;'],
                closeBtn: 1,
                shade: 0.3,
                content: content,
                area: ['70%', '70%'],
                shadeClose: true,
                resize: true,
                anim: 1,
                id: 'LAY_layuiroleas', //设定一个id，防止重复弹出
                moveType: 1,
                maxmin: false,
                success: function (layero, index) {
                    $('#cloudID').val('');
                    $('#name').val('');
                    $('#address').val('');
                    $('#createTimeScope').val('');
                    $('#minLon').val('');
                    $('#maxLon').val('');
                    $('#minLat').val('');
                    $('#maxLat').val('');
                    $('#curStatus').val(0);
                    form.render();

                    var active = {
                        reload: function () {
                            var cloudId = $('#cloudID').val();
                            var name = $('#name').val();
                            var address = $('#address').val();
                            var createTimeScope = $('#createTimeScope').val();
                            var minLon = $('#minLon').val();
                            var maxLon = $('#maxLon').val();
                            var minLat = $('#minLat').val();
                            var maxLat = $('#maxLat').val();
                            var status = $('#curStatus').val();
                            if (minLon != '' && maxLon != '' && minLon >= maxLon) {
                                layer.msg('下限不可大于等于上限');
                                return;
                            }
                            if (minLat != '' && maxLat != '' && minLat >= maxLat) {
                                layer.msg('下限不可大于等于上限');
                                return;
                            }
                            var param = {
                                cloudId: cloudId,
                                name: name,
                                address: address,
                                createTimeScope: createTimeScope,
                                minLon: minLon,
                                maxLon: maxLon,
                                minLat: minLat,
                                maxLat: maxLat,
                                status: status
                            };
                            tableInfo.reload({ //执行重载
                                where: {
                                    key: JSON.stringify(param) //转成json
                                },
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                },
                                done: function (res, curr, count) {
                                    this.where = {};
                                    layer.close(layer.index);
                                }
                            });
                        },

                        resetInfo: function () {
                            $('#cloudID').val('');
                            $('#name').val('');
                            $('#address').val('');
                            $('#createTimeScope').val('');
                            $('#minLon').val('');
                            $('#maxLon').val('');
                            $('#minLat').val('');
                            $('#maxLat').val('');
                            $('#curStatus').val(0);
                            form.render();
                        }
                    };
                    $('.reloadTable .layui-btn').on('click', function () {
                        var type = $(this).data('type');
                        active[type] ? active[type].call(this) : '';
                    });

                },
                cancel: function (index, layero) {
                    $('#cloudID').val('');
                    $('#name').val('');
                    $('#address').val('');
                    $('#createTimeScope').val('');
                    $('#minLon').val('');
                    $('#maxLon').val('');
                    $('#minLat').val('');
                    $('#maxLat').val('');
                    $('#status').val(0);
                    form.render();
                }
            });
        });
    });


    layui.use('laydate', function () { //日期
        var laydate = layui.laydate;
        laydate.render({
            elem: '#createTimeScope',
            type: 'datetime',
            range: true,
            format: 'yyyy-MM-dd HH:mm:ss',
            calendar: true
        });
    });

});